<template>
  <div class="home">
    <HomeNav
      :cur-division="curDivision"
      :division-list="divisionList"
      :activeTab="abnormalInfo"
      @switch="handleDivisionSwitch"
    >
      <van-tabs
        v-if="showVantabs"
        v-model:active="activeTab"
        class="home-tabs"
        @change="onIndustryChange"
      >
        <template v-for="item in industryListNoneNull" :key="item.name">
          <van-tab>
            <template #title>
              <div style="display: flex; text-align: center; line-height: 2.1">
                {{ item?.name }}
              </div>
            </template>
          </van-tab>
        </template>
      </van-tabs>
    </HomeNav>
    <AbnormalInfo :info="abnormalInfo" />
    <!-- <div>
      {{ curIndustry }}
    </div> -->
    <div ref="refList" class="content-list">
      <QuotaList />
    </div>
    <Tabbar :show-back-top="showBackTop" @handleClickItem="handleTabClick" />
    <VersionInfo
      :visible="updateVisible"
      :version-info="versionInfo"
      :force="force"
      @close="updateVisible = false"
    />
  </div>
</template>

<script lang="ts" setup>
import { storeToRefs } from 'pinia'
import { computed, ref, reactive, toRefs, watch, onActivated, getCurrentInstance } from 'vue'
// import { reactive, toRefs } from 'vue'
import { useScroll, useElementSize } from '@vueuse/core'
import { useQuotaStore, useUserStore } from '@/store'
import Tabbar from '@/components/Tabbar'
import VersionInfo from '@/views/my/components/VersionInfo.vue'

import HomeServe from '@/api/home'
import QuotaServe from '@/api/quota'
import type { ITabBarItem } from '@/components/Tabbar/src/type'
import type { IndustryItemOrNull } from '@/store/type'

import HomeNav from './components/HomeNav.vue'
import AbnormalInfo from './components/AbnormalInfo.vue'
import QuotaList from './components/QuotaList.vue'
import MyService from '@/api/my'
import { config } from '@/config'
defineOptions({
  name: 'Home'
})

// 检查更新
const updateVisible = ref<boolean>(false)
const versionInfo = ref({})
const force = ref(true)
const checkUpdate = () => {
  MyService.isForce().then(res => {
    force.value = res.force == 'true' ? true : false
    if (compareVersions(res.version, config.version) === 1) {
      versionInfo.value = res
      updateVisible.value = true
    }
    // MyService.getVersionInfo().then(res => {
    //   if (compareVersions(res.version, config.version) === 1) {
    //     versionInfo.value = res
    //     updateVisible.value = true
    //   }
    // })
  })
}

/**
 * 版本号比较
 * @param v1 新版本
 * @param v2 旧版本
 * @returns v1新则返回1，v2新则返回-1，相等则返回0
 */
const compareVersions = (v1: string, v2: string) => {
  const v1parts = v1.split('.')
  const v2parts = v2.split('.')
  for (let i = 0; i < v1parts.length; i++) {
    if (v2parts.length === i) {
      return 1
    }
    if (v1parts[i] === v2parts[i]) {
      continue
    } else if (v1parts[i] > v2parts[i]) {
      return 1
    } else {
      return -1
    }
  }
  if (v1parts.length !== v2parts.length) {
    return -1
  }
  return 0
}

checkUpdate()

// state
interface IState {
  curDivision: IDivisionItem | null
  curIndustry: IndustryItemOrNull
}

const state = reactive<IState>({
  curDivision: null,
  curIndustry: null
})

const activeTab = ref<number>(0)
const showVantabs = ref<boolean>(true)

// division
const divisionList = ref<IDivisionItem[]>([])

// abnormal info
const abnormalInfo = ref<IAbnormalInfo>()
watch(state, () => {
  if (state.curIndustry) {
    QuotaServe.getAbnormalInfo(state.curIndustry.key).then(res => {
      abnormalInfo.value = res.data
    })
  }
})

// backtop
const refList = ref<HTMLElement | null>(null)
const { y: scrollY } = useScroll(refList, {
  behavior: 'smooth'
})
const { height: listHeight } = useElementSize(refList)
const showBackTop = computed(() => {
  return scrollY.value > listHeight.value
})
const handleTabClick = (data: ITabBarItem) => {
  if (data.to == '/home' && showBackTop.value) {
    scrollY.value = 0
  }
}

// 行业列表
const quotaStore = useQuotaStore()
const { industryList } = storeToRefs(quotaStore)
const industryListNoneNull = computed(() => {
  let arr = []
  if (industryList.value.filter(i => !!i).filter(f => f.department == null).length > 0) {
    arr = [...industryList.value.filter(i => !!i).filter(f => f.department == null)]
  }
  industryList.value
    .filter(i => !!i)
    .map(m => {
      if (m.department !== null) {
        arr.push(m)
      }
    })
  return arr
})

// avoid tab indicator bug
watch(industryList, () => {
  showVantabs.value = false
  setTimeout(() => {
    showVantabs.value = true
    scrollY.value = 0
  }, 200)
})

const initQuotaList = () => {
  if (industryListNoneNull.value.length) {
    if (!state.curIndustry) {
      state.curIndustry = industryListNoneNull.value[0]
    }
    if (state.curIndustry) {
      console.log(
        quotaStore.fetchQuotaList({
          type: state.curIndustry.key
        }),
      )
      return quotaStore.fetchQuotaList({
        type: state.curIndustry.key
      })
    }
  }
  return Promise.reject()
}

const initIndustyList = () => {
  const userStore = useUserStore()
  const id = userStore.userInfo.id
  quotaStore.$patch({
    quotaList: []
  })
  return quotaStore
    .fetchIndustryList({
      division: state.curDivision?.division,
      id
    })
    .then(() => {
      state.curIndustry = null
      return initQuotaList()
    })
}

const initDivisionList = () => {
  return HomeServe.getDivisionList().then(resp => {
    // move 环境卫生 to first
    const targetIdx = resp.data.findIndex((d: IDivisionItem) => {
      return d.division == '环境卫生'
    })
    if (targetIdx > -1) {
      const target = resp.data.splice(targetIdx, 1)
      resp.data.unshift(target[0])
    }

    divisionList.value = resp.data
    state.curDivision = divisionList.value[0]
    return initIndustyList()
  })
}

initDivisionList()
onActivated(() => {
  if (state.curIndustry) {
    initQuotaList()
  }
})

// industry tab switch
const onIndustryChange = (idx: number) => {
  state.curIndustry = industryListNoneNull.value[idx]
  activeTab.value = idx
  if (state.curIndustry) {
    console.log(state.curIndustry)
    initQuotaList()
  }
}

const handleDivisionSwitch = (idx: number) => {
  activeTab.value = 0
  state.curDivision = divisionList.value[idx]
  initIndustyList()
}

const { curDivision } = toRefs(state)
</script>

<script lang="ts">
export interface IDivisionItem {
  division: string
}

export interface IAbnormalInfo {
  total: number
  anomalyIndex: number
}
</script>

<style lang="less" scoped>
.home {
  height: 100vh;
  background-color: #fff;
  box-sizing: border-box;
  overflow: auto;
  display: flex;
  flex-direction: column;
  .home-tabs {
    border-radius: 19.23px 19.23px 0px 0px;
    overflow: hidden;

    :deep(.van-tab__text) {
      // font-size: 12.18px;
      font-size: 13.18px;
    }
  }

  .content-list {
    flex-grow: 1;
    overflow-y: scroll;
  }
}
</style>
